package com.nowcoder.community.config;

import com.nowcoder.community.contant.Role;
import com.nowcoder.community.utils.CommunityUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略静态资源
        web.ignoring()
                .antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 权限管理
        http.authorizeRequests()
                    .antMatchers(
                            "/comment/**",
                            "/discuss/add",
                            "/follow/**",
                            "/letter/**",
                            "/like/**",
                            "/logout/**",
                            "/notice/**",
                            "/user/setting",
                            "/user/upload",
                            "user/updateHeaderUrl",
                            "/user/update_password",
                            "/user/reply/**"
                    )
                    .hasAnyAuthority(Role.USER, Role.ADMIN, Role.MODERATOR)
                .antMatchers(
                        "/discuss/top",
                        "/discuss/wonderful"
                ).hasAnyAuthority(Role.MODERATOR, Role.ADMIN)
                .antMatchers(
                        "/discuss/delete",
                        "/data/**",
                        "/actuator/**")
                .hasAuthority(Role.ADMIN)
                .anyRequest().permitAll();

        // 权限不够处理
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override // 没有登录时
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        if (isAjaxRequest(request)){
                            // 异步请求
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.print(CommunityUtils.getJsonString(403, "用户未登录"));
                        }else {
                            // 普通 HTTP 请求
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override // 权限不够时
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        if (isAjaxRequest(request)){
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.print(CommunityUtils.getJsonString(403, "您没有访问此功能的权限"));
                        }else{
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });

        // 绕过 Spring Security 的退出功能
        http.logout()
                .logoutUrl("security-logout");

    }

    private boolean isAjaxRequest(HttpServletRequest request){
        String header = request.getHeader("X-Requested-With");
        if (header == null || !header.equals("XMLHttpRequest"))
            return false;
        return true;
    }
}
